package com.riko.comic.module.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.riko.comic.module.sys.bean.po.User;
import com.riko.comic.module.sys.bean.vo.UserVo;
import com.riko.comic.module.sys.mapper.UserMapper;
import com.riko.comic.module.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Sun
 * @since 2021-11-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder encoder;

    @Override
    public void register(User user) {
    }


    @Override
    public Boolean login(HttpServletResponse response,HttpServletRequest request, UserVo userVo) {
        HttpSession httpSession = request.getSession();

        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, userVo.getUser().getUsername()));
        Boolean userState = false;//登录状态
        if (user != null) {
            if (encoder.matches(userVo.getUser().getPassword(),user.getPassword())) {
                userState = true;
                httpSession.setAttribute("loginUserId", user.getId());
                System.out.println();
            }
        }
        if (Objects.equals(userVo.getRememberPW(), "true")) {
            String cookieMessage = null;
            try {
                cookieMessage = URLEncoder.encode("username=" + userVo.getUser().getUsername(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Cookie cookie = new Cookie("user", cookieMessage);
            cookie.setMaxAge(604800);
            response.addCookie(cookie);
        } else {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("user")) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                        break;
                    }
                }
            }
        }
        return userState;
    }

    @Override
    public String registerCheck(User user) {
        String usernameM = usernameCheck(user.getUsername());
        String passwordM = passwordCheck(user.getPassword());
        if (usernameM.isEmpty() && passwordM.isEmpty()) {
            user.setNick(user.getUsername());
            user.setPassword(encoder.encode(user.getPassword()));
            user.setSex("保密");
            user.setPic("image/a29f385da5c84dc2985309c74488c9a4");
            save(user);
        }
        return "{\"username\":\"" + usernameM + "\"," +
                "\"password\":\"" + passwordM + "\"}";
    }

    @Override
    public String usernameCheck(String username) {
        if (username.length() > 15) {
            return "昵称过长，长度在3~15个字符之间";
        } else if (username.length() < 3) {
            return "昵称过短，长度在3~15个字符之间";
        } else if (!username.matches("^[\\u4E00-\\u9FA5A-Za-z0-9_]+$")) {
            return "用户名不得含有除 下划线\"_\" 外的特殊字符";
        } else {
            User user = getOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, username));
            if (user != null) {
                return "昵称已被占用";
            } else {
                return "";
            }
        }
    }

    @Override
    public String passwordCheck(String password) {
        if (!password.matches("^[a-zA-Z]\\w{5,15}$")) {
            return "密码以字母开头，长度在6~16之间，只能包含字母、数字和下划线";
        } else {
            return "";
        }
    }
}
